# python 3.6
import random
import time
import configparser
import os
from paho.mqtt import client as mqtt_client

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
cf = configparser.ConfigParser()
cf.read(os.path.join(BASE_DIR,'config.ini'), encoding='UTF-8')
secs = cf.sections()
# 免费的Broker
host = cf.get("mqtt", "host")
port = int(cf.get("mqtt", "port"))
username=cf.get("mqtt","userName")
password=cf.get("mqtt","userPassWorld")
send_message_topic=cf.get("mqtt","send_message_topic")
client_id=f'ketang-{random.randint(0,1000)}' #唯一设备号
auth={
    "username":username,
    "password":password
}
# 连接函数
def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    # Set Connecting Client ID
    client = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION1,client_id)
    client.username_pw_set(username, password)
    client.on_connect = on_connect
    client.connect(host, port)
    return client


def publish(client):
    msg_count = 0
    while True:
        time.sleep(1)
        msg = f"messages: {msg_count}"
        result = client.publish(send_message_topic, msg)	# 指定信息的tpoic和信息内容，并发送
        # result: [0, 1]
        status = result[0]	# 解析响应内容
        if status == 0:	# 发送成功
            print(f"Send `{msg}` to topic `{send_message_topic}`")
        else:	# 发送失败
            print(f"Failed to send message to topic {send_message_topic}")
        msg_count += 1





if __name__ == '__main__':
    client = connect_mqtt()		# 连接
    client.loop_start()	# 新线程loop
    publish(client)	# 发送
